<template>
	<van-nav-bar title="验证邮箱" left-text="返回" left-arrow @click-left="onBack" />
	<van-form @submit="onSubmit">
		<van-cell-group inset>
			<van-field v-model="business.email" name="email" label="邮箱" readonly />
			<van-field v-model="business.code" name="code" label="验证码" placeholder="验证码" />
			<div style="height: 10px;"></div>
			<van-button size="small" v-show="btnShow === true" type="primary" @click="send">发送验证码</van-button>
			<van-button size="small" v-show="btnShow === false" type="primary">
				<van-count-down ref="countDown" millisecond :auto-start="false" :time="time" format="ss"
					@finish="onFinish" />
			</van-button>
		</van-cell-group>
		<div style="margin: 16px;">
			<van-button round block type="primary" native-type="submit">
				提交
			</van-button>
		</div>
	</van-form>

</template>
<script setup>
import { ref, getCurrentInstance, reactive } from 'vue';

const { proxy } = getCurrentInstance();
const business = reactive(proxy.$cookies.get('business') ?? {});
const code = ref('');
const time = ref(60 * 1000);
const btnShow = ref(true);
const countDown = ref(null);
const data = {
	email: business.email
};
const send = async () => {

	let result = await proxy.$Api.send(data);
	if (result && result.code === 1) {
		proxy.$showNotify({
			type: 'success',
			message: result.msg,
			duration: 2000,
		});
		btnShow.value = false;
		countDown.value.start();
		console.log(result);
		return;
	} else {
		proxy.$showNotify({
			type: 'warning',
			message: result.msg,
			duration: 2000
		});

		return;
	}


}

const onSubmit = async (values) => {
	const data = {
		id: business.id,
		email: values.email,
		code: values.code,
	}
	let result = await proxy.$Api.emailValidate(data);
	if (result && result.code === 1) {
		proxy.$showNotify({
			type: 'success',
			message: result.msg,
			duration: 2000,
			onClose: () => {
				proxy.$router.back();
			}
		});


		return;
	} else {
		proxy.$showNotify({
			type: 'warning',
			message: result.msg,
			duration: 2000
		});

		return;
	}
}

const onFinish = () => {
	btnShow.value = true;
	countDown.value.reset();
}

const onBack = () => {
	proxy.$router.back();
}
</script>